<?php

class Application_Model_ParticipantesBolaoMapper
{
    protected $_dbTabelaBolaoParticipantes;

    public function setDBTable($tabelaBD)
    {
        if (is_string($tabelaBD)) {
            $tabelaBD = new $tabelaBD();
        }
        if (!$tabelaBD instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Tabela invalida');
        }
        $this->_dbTabelaBolaoParticipantes = $tabelaBD;
        return $this;
    }

    public function getDBTable()
    {
        if (null === $this->_dbTabelaBolaoParticipantes) {
            $this->setDBTable('Application_Model_DbTable_ParticipantesBolao');
        }
        return $this->_dbTabelaBolaoParticipantes;
    }

    public function inserir(Application_Model_ParticipantesBolao $gerencia)
    {
        $dados = array(
            'id_bolao' => $gerencia->getId(),
            'email_participante' => $gerencia->getEmail(),
        );

        $this->getDBTable()->insert($dados);
    }

    public function buscar($email, $inicio, $total)
    {
        $tabela = $this->getDBTable();

        $select = $tabela->select();
        $select->from($tabela, 'id_bolao')
               ->where('email_participante = ?', $email)
               ->limit($total, $inicio);

        return $tabela->fetchAll($select);
    }

    public function getTotalBoloesPendentes($email) {

        $tabela = $this->getDBTable();

        $select = $tabela->select();
        $select->from($tabela, '*')
               ->where('email_participante = ?', $email);

        $linhas = $tabela->fetchAll($select);

        return count($linhas);
    }

    public function remove($id_bolao, $email)
    {
        $tabela = $this->getDBTable();

        $where[] = $tabela->getAdapter()->quoteInto('id_bolao = ?', $id_bolao);
        $where[] = $tabela->getAdapter()->quoteInto('email_participante = ?', $email);                        

        return $tabela->delete($where);
    }

    public function existe($id_bolao, $email)
    {
        $tabela = $this->getDBTable();

        $select = $tabela->find($id_bolao, $email);

        if(count($select) == 0)
            return false;

        return true;
    }

    public function insereParticipante($idBolao, $emailParticipante)
    {
        $dados = array(
            'id_bolao' => $idBolao,
            'email_participante' => $emailParticipante
        );

        $this->getDBTable()->insert($dados);
    }

}

